package com.Lemon.Zhkuhealth.provider.service.impl;

import com.Lemon.Zhkuhealh.api.service.IMemberService;
import com.Lemon.Zhkuhealh.api.service.IReserveService;
import com.Lemon.Zhkuhealth.common.pojo.entity.Member;
import com.Lemon.Zhkuhealth.common.pojo.entity.Reserve;
import com.Lemon.Zhkuhealth.common.pojo.vo.OrderTypeCountVO;
import com.Lemon.Zhkuhealth.common.pojo.vo.OrderStatusCountVO;

import com.Lemon.Zhkuhealth.common.pojo.vo.ReserveVo;
import com.Lemon.Zhkuhealth.common.util.PageResult;
import com.Lemon.Zhkuhealth.common.util.QueryPageBean;
import com.Lemon.Zhkuhealth.provider.mapper.ReserveMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService; // 确保使用Dubbo的@DubboService
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@DubboService // 标记这是一个Dubbo服务
@Service
@Slf4j
public class ReserveServiceImpl extends ServiceImpl<ReserveMapper, Reserve> implements IReserveService {
    @Autowired
    private ReserveMapper reserveMapper;

    @DubboReference // 引用会员服务，用于查询会员姓名
    private IMemberService memberService;

    @Override
    public PageResult<ReserveVo> findPage(QueryPageBean queryPageBean) {
        log.info("查询预约列表，当前页: {}, 每页大小: {}, 查询条件: {}",
                queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());

        Page<Reserve> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        LambdaQueryWrapper<Reserve> queryWrapper = new LambdaQueryWrapper<>();

        // 可以在这里添加根据查询字符串对预约日期、类型等进行过滤的逻辑
        // 根据MemberArchives.vue的查询，这里queryString可能包含姓名或手机号
        // 但Reserve表本身没有姓名或手机号，所以需要在Service层进行处理

        // 如果queryString是针对会员姓名的，需要先查询会员ID
        // 目前queryPageBean的queryString只支持一个通用字符串，如果需要按姓名查询，需要扩展QueryPageBean
        // 这里暂时只支持简单的模糊匹配预约类型、状态等字段，或直接返回所有
        // 假设 queryPageBean.getQueryString() 可以是预约类型或状态
        if (StringUtils.hasText(queryPageBean.getQueryString())) {
            queryWrapper.like(Reserve::getOrderType, queryPageBean.getQueryString())
                    .or()
                    .like(Reserve::getOrderStatus, queryPageBean.getQueryString())
                    .or()
                    .like(Reserve::getOrderDate, queryPageBean.getQueryString()); // 简单示例，实际日期可能需要范围查询
        }

        // 默认按预约日期降序排序
        queryWrapper.orderByDesc(Reserve::getOrderDate);

        Page<Reserve> reservePage = reserveMapper.selectPage(page, queryWrapper);

        List<Reserve> reserveList = reservePage.getRecords();
        List<ReserveVo> reserveVoList = new ArrayList<>();

        if (!reserveList.isEmpty()) {
            // 收集所有 memberId
            List<Integer> memberIds = reserveList.stream()
                    .map(Reserve::getMemberId)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询会员信息 (如果IMemberService支持批量查询更好，这里假设单个查询)
            // 更好的方式是在MemberService中提供一个List<Member> findByIds(List<Integer> ids)
            Map<Integer, String> memberNameMap = memberIds.stream()
                    .collect(Collectors.toMap(
                            id -> id,
                            id -> {
                                try {
                                    Member member = memberService.findById(id);
                                    return member != null ? member.getName() : "未知会员";
                                } catch (Exception e) {
                                    log.error("查询会员ID: {} 失败: {}", id, e.getMessage());
                                    return "查询失败";
                                }
                            }
                    ));

            // 组装 ReserveVo 列表
            for (Reserve reserve : reserveList) {
                ReserveVo reserveVo = new ReserveVo();
                BeanUtils.copyProperties(reserve, reserveVo); // 拷贝Reserve的属性
                reserveVo.setMemberName(memberNameMap.getOrDefault(reserve.getMemberId(), "未知会员"));
                reserveVoList.add(reserveVo);
            }
        }
        return new PageResult<>(reservePage.getTotal(), reserveVoList);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        log.info("删除预约，ID: {}", id);
        reserveMapper.deleteById(id);
        log.info("预约删除成功，ID: {}", id);
    }

    @Override
    @Transactional
    public void add(Reserve reserve) {
        log.info("新增预约: {}", reserve);
        reserveMapper.insert(reserve);
        log.info("预约新增成功，ID: {}", reserve.getId());
    }

    @Override
    public Reserve findById(Integer id) {
        log.info("根据ID查询预约: {}", id);
        return reserveMapper.selectById(id);
    }

    @Override
    @Transactional
    public void edit(Reserve reserve) {
        log.info("更新预约信息: {}", reserve);
        reserveMapper.updateById(reserve);
        log.info("预约更新成功，ID: {}", reserve.getId());
    }

    @Override
    public List<OrderTypeCountVO> getOrderTypeDistribution() {
        // Step 1: 从数据库获取所有原始的 Reserve 记录
        // 注意：selectList(null) 会查询表中所有记录，数据量大时会影响性能和内存
        List<Reserve> allReserves = reserveMapper.selectList(null);

        // Step 2: 在 Java 后端使用 Stream API 进行分组和计数
        Map<String, Long> orderTypeCounts = allReserves.stream()
                // 过滤掉 orderType 为 null 的情况，以避免 NullPointerException
                .filter(reserve -> reserve.getOrderType() != null)
                .collect(Collectors.groupingBy(Reserve::getOrderType, Collectors.counting()));

        // Step 3: 将统计结果转换为 List<OrderTypeCountVO>
        return orderTypeCounts.entrySet().stream()
                .map(entry -> {
                    OrderTypeCountVO vo = new OrderTypeCountVO();
                    vo.setOrderType(entry.getKey());
                    vo.setCount(entry.getValue());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<OrderStatusCountVO> getOrderStatusDistribution() {
        // Step 1: 从数据库获取所有原始的 Reserve 记录
        List<Reserve> allReserves = reserveMapper.selectList(null);

        // Step 2: 在 Java 后端使用 Stream API 进行分组和计数
        Map<String, Long> orderStatusCounts = allReserves.stream()
                // 过滤掉 orderStatus 为 null 的情况
                .filter(reserve -> reserve.getOrderStatus() != null)
                .collect(Collectors.groupingBy(Reserve::getOrderStatus, Collectors.counting()));

        // Step 3: 将统计结果转换为 List<OrderStatusCountVO>
        return orderStatusCounts.entrySet().stream()
                .map(entry -> {
                    OrderStatusCountVO vo = new OrderStatusCountVO();
                    vo.setOrderStatus(entry.getKey());
                    vo.setCount(entry.getValue());
                    return vo;
                })
                .collect(Collectors.toList());
    }
}